package com.delamer.facile.exe;

import com.delamer.facile.db.DBUtilTpa;
import com.delamer.facile.obj.ObjectTpa;
import com.delamer.utils.MsgUtil;
import com.delamer.utils.PermitUtil;
import net.md_5.bungee.api.chat.ClickEvent;
import net.md_5.bungee.api.chat.TextComponent;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

public class ExecutorTpa {
    public void help(CommandSender sender, String[] args) throws Exception {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(Bukkit.getPluginManager().getPlugin("DelamerFacile").getResource("tpa.help"), "UTF-8"));
        List<String> results = new ArrayList<String>();
        String line = null;
        while ((line = bufferedReader.readLine()) != null)
            results.add(line);
        sender.sendMessage(results.toArray(new String[]{}));
    }

    public void apply(CommandSender sender, String[] args) throws Exception {
        if (!(sender instanceof Player)) {
            sender.sendMessage(MsgUtil.err("该指令无法通过控制台使用"));
            return;
        }
        if(!PermitUtil.hasPermit(sender.getName(),"tpa.apply")){
            sender.sendMessage(MsgUtil.err("未取得授权的玩家无法使用该指令"));
            return;
        }
        if (args.length < 2) {
            sender.sendMessage(MsgUtil.err("请输入目标玩家ID"));
            return;
        }
        Player target = Bukkit.getPlayerExact(args[1]);
        if (target == null) {
            sender.sendMessage(MsgUtil.err("目标玩家不存在"));
            return;
        }
        String userName = sender.getName();
        String targetName = args[1];

        ObjectTpa object = DBUtilTpa.getTpa(userName, targetName);
        if (object == null) {
            object = new ObjectTpa() {{
                setUserName(userName);
                setTargetName(targetName);
                setIsCome(0);
            }};
            DBUtilTpa.addTpa(object);
        } else {
            int effect = Bukkit.getPluginManager().getPlugin("DelamerFacile").getConfig().getInt("tpapply.effect");
            int between = (int) (Math.abs(object.getCreateTime().getTime() - Calendar.getInstance().getTimeInMillis()) / 1000);
            if (between < effect) {
                sender.sendMessage(MsgUtil.err("发起传送申请失败，上一条时限内的传送申请未被处理"));
                return;
            } else {
                object = new ObjectTpa() {{
                    setUserName(userName);
                    setTargetName(targetName);
                    setIsCome(0);
                }};
                DBUtilTpa.setTpa(object);
            }
        }
        sender.sendMessage(MsgUtil.msg("发起传送申请成功：§b" + targetName));

        TextComponent message = new TextComponent("§b" + sender.getName() + "§e申请传送到你的位置：");
        TextComponent accept = new TextComponent("§r[§a接受§r]");
        TextComponent reject = new TextComponent("§r[§c拒绝§r]");
        accept.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/tpa accept " + userName));
        reject.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/tpa reject " + userName));
        message.addExtra(accept);
        message.addExtra("§r｜");
        message.addExtra(reject);
        target.spigot().sendMessage(message);
    }

    public void here(CommandSender sender, String[] args) throws Exception {
        if (!(sender instanceof Player)) {
            sender.sendMessage(MsgUtil.err("该指令无法通过控制台使用"));
            return;
        }
        if(!PermitUtil.hasPermit(sender.getName(),"tpa.here")){
            sender.sendMessage(MsgUtil.err("未取得授权的玩家无法使用该指令"));
            return;
        }
        if (args.length < 2) {
            sender.sendMessage(MsgUtil.err("请输入目标玩家ID"));
            return;
        }
        Player target = Bukkit.getPlayerExact(args[1]);
        if (target == null) {
            sender.sendMessage(MsgUtil.err("目标玩家不存在"));
            return;
        }
        String userName = sender.getName();
        String targetName = args[1];

        ObjectTpa object = DBUtilTpa.getTpa(userName, targetName);
        if (object == null) {
            object = new ObjectTpa() {{
                setUserName(userName);
                setTargetName(targetName);
                setIsCome(1);
            }};
            DBUtilTpa.addTpa(object);
        } else {
            int effect = Bukkit.getPluginManager().getPlugin("DelamerFacile").getConfig().getInt("tpapply.effect");
            int between = (int) (Math.abs(object.getCreateTime().getTime() - Calendar.getInstance().getTimeInMillis()) / 1000);
            if (between < effect) {
                sender.sendMessage(MsgUtil.err("发起传送申请失败，上一条时限内的传送申请未被处理"));
                return;
            } else {
                object = new ObjectTpa() {{
                    setUserName(userName);
                    setTargetName(targetName);
                    setIsCome(1);
                }};
                DBUtilTpa.setTpa(object);
            }
        }
        sender.sendMessage(MsgUtil.msg("发起传送申请成功：§b" + targetName));

        TextComponent message = new TextComponent("§b" + sender.getName() + "§e申请将你传送到他的位置：");
        TextComponent accept = new TextComponent("§r[§a接受§r]");
        TextComponent reject = new TextComponent("§r[§c拒绝§r]");
        accept.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/tpa accept " + userName));
        reject.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/tpa reject " + userName));
        message.addExtra(accept);
        message.addExtra("§r｜");
        message.addExtra(reject);
        target.spigot().sendMessage(message);
    }

    public void accept(CommandSender sender, String[] args) throws Exception {
        if (!(sender instanceof Player)) {
            sender.sendMessage(MsgUtil.err("该指令无法通过控制台使用"));
            return;
        }
        String userName = null;
        if (! (args.length < 2)) {
            userName = args[1];
        }
        if (userName != null) {
            if (Bukkit.getPlayerExact(userName) == null) {
                sender.sendMessage(MsgUtil.err("目标玩家不存在"));
                return;
            }
        }
        String targetName = sender.getName();
        ObjectTpa objectTpa = new ObjectTpa();
        objectTpa.setUserName(userName);
        objectTpa.setTargetName(targetName);
        if (userName == null)
            objectTpa.setIsCome(-1);
        List<ObjectTpa> list = DBUtilTpa.getTpaList(objectTpa);
        if (list.size() == 0) {
            sender.sendMessage(MsgUtil.err("不存在未处理的传送申请"));
        } else {
            for (ObjectTpa obj : list) {
                DBUtilTpa.delTpa(obj);
                int effect = Bukkit.getPluginManager().getPlugin("DelamerFacile").getConfig().getInt("tpapply.effect");
                int between = (int) (Math.abs(obj.getCreateTime().getTime() - Calendar.getInstance().getTimeInMillis()) / 1000);
                if (between < effect) {
                    sender.sendMessage(MsgUtil.err("接受玩家§b" + obj.getUserName() + "§e传送申请失败，该传送申请已超时"));
                    return;
                } else {
                    Player player = Bukkit.getPlayerExact(obj.getUserName());
                    if (player != null) {
                        if (obj.getIsCome()>0)
                            ((Player) sender).teleport(player.getLocation());
                        else
                            player.teleport(((Player) sender).getLocation());

                        sender.sendMessage(MsgUtil.msg("接受传送申请成功，§b" + player.getName() + (obj.getIsCome() > 0 ? "§e将要传送到你的位置" : "§e将你传送到他的位置")));
                        player.sendMessage(MsgUtil.msg("§b" + targetName + "§e已接受你的传送申请，§b" + targetName + (obj.getIsCome() > 0 ? "§e将要传送到你的位置" : "§e将你传送到他的位置")));
                    } else {
                        sender.sendMessage(MsgUtil.msg("接受传送申请成功，但玩家§b" + obj.getUserName() + "§e不在线，传送执行失败"));
                    }
                }
            }
        }
    }

    public void reject(CommandSender sender, String[] args) throws Exception {
        if (!(sender instanceof Player)) {
            sender.sendMessage(MsgUtil.err("该指令无法通过控制台使用"));
            return;
        }
        String userName = null;
        if (! (args.length < 2)) {
            userName = args[1];
        }
        if (userName != null) {
            if (Bukkit.getPlayerExact(userName) == null) {
                sender.sendMessage(MsgUtil.err("目标玩家不存在"));
                return;
            }
        }
        String targetName = sender.getName();
        ObjectTpa objectTpa = new ObjectTpa();
        objectTpa.setUserName(userName);
        objectTpa.setTargetName(targetName);
        List<ObjectTpa> list = DBUtilTpa.getTpaList(objectTpa);
        if (list.size() == 0) {
            sender.sendMessage(MsgUtil.err("不存在未处理的传送申请"));
        } else {
            for (ObjectTpa obj : list) {
                DBUtilTpa.delTpa(obj);
                Player player = Bukkit.getPlayerExact(obj.getUserName());
                if (player != null) {
                    sender.sendMessage(MsgUtil.msg("你已拒绝玩家§b" + player.getName() + "§e的传送申请"));
                    player.sendMessage(MsgUtil.msg("§b" + targetName + "§e已拒绝你的传送申请"));
                } else {
                    sender.sendMessage(MsgUtil.msg("你已拒绝玩家§b" + obj.getUserName() + "§e的传送申请"));
                }
            }
        }
    }
}
